#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

# Copyright (c) 2019-2020 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

"""
in_focus - Define and access the "in focus" database

@author: Fpemud
@license: GPLv3 License
@contact: fpemud@sina.com
"""


import os
import functools

__author__ = "fpemud@sina.com (Fpemud)"
__version__ = "0.0.1"


def get_categories(self):
    return [m.CATEGORY for m in _getCategoryModuleDict().values()]


class Database:

    def lock(self, category_name):
        assert False

    def unlock(self, category_name):
        assert False

    def get_items(self, category_name=None):
        assert False

    def has_item(self, category_name, item_name):
        assert False

    def add_item(self, category_name, item_name):
        assert False

    def remove_item(self, category_name, item_name):
        assert False


class SystemDatabase(Database):

    def __init__(self, root_dir="/"):
        self._rootDir = root_dir

    def get_items(self, category_name=None):
        if category_name is None:
            moduleList = self._getCategoryModuleDict().values()
        else:
            moduleList = [self._getCategoryModuleDict()[category_name]]

        sysDir = os.path.join(self._rootDir, "usr/share/in-focus-db")
        runDir = os.path.join(self._rootDir, "run/in-focus-db")
        etcDir = os.path.join(self._rootDir, "etc/in-focus-db")

        ret = []
        for m in moduleList:
            ret += m.scan_items([os.path.join(sysDir, m.CATEGORY.name), os.path.join(runDir, m.CATEGORY.name)],
                                [os.path.join(etcDir, m.CATEGORY.name)],
                                [])
        return ret


class UserDatabase(Database):

    def __init__(self, home_dir):
        self._homeDir = home_dir

    def get_items(self, category_name=None):
        if category_name is None:
            moduleList = self._getCategoryModuleDict().values()
        else:
            moduleList = [self._getCategoryModuleDict()[category_name]]

        userDir = os.path.join(self._homeDir, ".config/in-focus-db")

        ret = []
        for m in moduleList:
            ret += m.scan_items([], [], [os.path.join(userDir, m.CATEGORY.name)])
        return ret


class Category:

    def __init__(self, name, description):
        self.name = name
        self.descrption = description


class ItemBase:

    @property
    def name(self):
        pass

    @property
    def category(self):
        pass


class FormatError(Exception):
    pass


class ScanItemError(Exception):
    pass


@functools.cache
def _getCategoryModuleDict():
    selfDir = os.path.dirname(os.path.realpath(__file__))
    ret = {}
    for fn in os.listdir(os.path.join(selfDir, "categories")):          # FIMXE: should use python module interface
        if fn.startswith("__"):                                         # filter __pycache__ directory
            continue
        if os.path.isdir(os.path.join(selfDir, "categories", fn)):
            exec("from .categories import %s" % (fn))
            m = eval(fn)
            ret[m.CATEGORY.name] = m
    return ret
